package com.ruoyi.activity.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.activity.domian.RedPacketConfig;
import com.ruoyi.activity.domian.RedPacketLimitConfig;
import com.ruoyi.activity.domian.RedPacketLimitParameter;
import com.ruoyi.activity.mapper.RedPacketConfigDao;
import com.ruoyi.activity.mapper.RedPacketLimitConfigDao;
import com.ruoyi.activity.mapper.RedPacketLimitParameterDao;
import com.ruoyi.activity.entity.RedPacketLimitVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@DataSource(DataSourceType.SLAVE)
public class RedPacketServiceImpl {

    @Resource
    private RedPacketConfigDao redPacketConfigDao;

    @Resource
    private RedPacketLimitConfigDao redPacketLimitConfigDao;

    @Resource
    private RedPacketLimitParameterDao redPacketLimitParameterDao;

    public Page<RedPacketLimitVO> getConfigList(Integer type, Integer isNeedRobot, String beginTime, String endTime, int pageNum, int pageSize){
        Page<RedPacketLimitVO> result = new Page<>();
        LambdaQueryWrapper<RedPacketConfig> queryWrapper = new LambdaQueryWrapper<>();
        if (type != null){
            queryWrapper.eq(RedPacketConfig::getType, type);
        }

        if (isNeedRobot != null){
            queryWrapper.eq(RedPacketConfig::getNeedRobot,isNeedRobot);
        }

        if (StringUtils.isNotEmpty(beginTime) && StringUtils.isNotEmpty(endTime)){
            queryWrapper.ge(RedPacketConfig::getCreateTime,beginTime);
            queryWrapper.le(RedPacketConfig::getCreateTime,endTime);
        }

        Page<RedPacketConfig> page = redPacketConfigDao.selectPage(new Page<>(pageNum,pageSize),queryWrapper);
        List<RedPacketConfig> configList = page.getRecords();
        if (CollUtil.isEmpty(configList)){
            return result;
        }

        List<RedPacketLimitParameter> parameters = redPacketLimitParameterDao.selectList(new QueryWrapper<>());
        if (CollUtil.isEmpty(parameters)){
            return result;
        }

        List<RedPacketLimitVO> limitVOList = BeanUtil.copyToList(configList, RedPacketLimitVO.class);
        Map<Long, RedPacketLimitParameter> nameMap = parameters.stream()
                .collect(Collectors.groupingBy(RedPacketLimitParameter::getId,Collectors.collectingAndThen(Collectors.toList(), v -> v.get(0))));
        limitVOList.forEach(e->{
            RedPacketLimitConfig limitConfig = redPacketLimitConfigDao.selectOne(new LambdaQueryWrapper<RedPacketLimitConfig>()
                    .eq(RedPacketLimitConfig::getType,e.getType())
                    .eq(RedPacketLimitConfig::getEnabled,true));
            if (limitConfig == null){
                return;
            }

            String json = limitConfig.getExtraParameter();
            if (StringUtils.isEmpty(json)){
                return;
            }

            List<Long> ids = JSONArray.parseArray(json,Long.class);
            List<String> params = new ArrayList<>(4);
            ids.forEach(id->{
                RedPacketLimitParameter parameter = nameMap.get(id);
                if (parameter != null){
                    if (parameter.getType() == 1){
                        params.add(parameter.getParameter() + parameter.getDescription());
                    } else if (parameter.getType() == 2){
                        params.add(parameter.getDescription());
                    }
                }
            });
            e.setParameters(String.join(",", params));
        });

        result.setRecords(limitVOList);
        return result;
    }

    /**
     * 添加红包基础配置
     * @author chengjian
     * @date 2021/9/9 6:15 下午
     * @param config 配置信息
     */
    public void addConfig(RedPacketConfig config){
        redPacketConfigDao.insert(config);
        addOrUpdateLimitConfig(config);
    }

    /**
     * 获取红包配置信息
     * @author chengjian
     * @date 2021/9/9 6:15 下午
     * @param id 主键id
     */
    public RedPacketConfig getConfig(Long id){
        return redPacketConfigDao.selectById(id);
    }

    /**
     * 更新红包配置信息
     * @author chengjian
     * @date 2021/9/9 6:16 下午
     * @param config 配置信息
     */
    public void updateConfig(RedPacketConfig config){
        config.setUpdateTime(null);
        redPacketConfigDao.updateById(config);

       addOrUpdateLimitConfig(config);
    }

    /**
     * 更新红包类型绑定连接条件池数据信息
     * @author chengjian
     * @date 2021/9/9 6:16 下午
     * @param config 绑定信息
     */
    private void addOrUpdateLimitConfig(RedPacketConfig config){
        List<Long> ids = Arrays.stream(config.getParameterIds()).filter(e->e > 0).collect(Collectors.toList());
        String json = JSON.toJSONString(ids);

        RedPacketLimitConfig limitConfig = redPacketLimitConfigDao
                .selectOne(new LambdaQueryWrapper<RedPacketLimitConfig>()
                        .eq(RedPacketLimitConfig::getType,config.getType())
                        .eq(RedPacketLimitConfig::getEnabled,true));
        if (limitConfig == null){
            limitConfig = new RedPacketLimitConfig();
            limitConfig.setExtraParameter(json);
            limitConfig.setEnabled(true);
            limitConfig.setType(config.getType());
            redPacketLimitConfigDao.insert(limitConfig);
            return;
        }
        limitConfig.setExtraParameter(json);
        redPacketLimitConfigDao.updateById(limitConfig);
    }

    /**
     * 删除红包配置
     * @author chengjian
     * @date 2021/9/9 6:17 下午
     * @param ids 列表
     */
    public void delConfig(List<Long> ids){
        List<RedPacketConfig> configList = redPacketConfigDao.selectBatchIds(ids);
        redPacketLimitConfigDao.delete(new LambdaQueryWrapper<RedPacketLimitConfig>()
                .in(RedPacketLimitConfig::getType,configList.stream().map(RedPacketConfig::getType).collect(Collectors.toList()))
                .eq(RedPacketLimitConfig::getEnabled,true));
        redPacketConfigDao.deleteBatchIds(ids);
    }
}
